const log4js = require('log4js');
const {formatError, formatRes} = require('./formatLog')
let logger = {}

log4js.configure({
  appenders: {
    error: {
      type: 'dateFile',
      pattern: 'yyyy-MM-dd.log',
      filename: __dirname + '/../logs/errors/',
      alwaysIncludePattern: true,
      errLogger: 'errLogger',
      maxLogSize: 104800, // 文件最大存储空间
      backups: 100  //当文件内容超过文件存储空间时，备份文件的数量
    },
    response: {
      type: 'dateFile',
      pattern: 'yyyy-MM-dd.log',
      category: 'resLogger',
      filename: __dirname + '/../logs/responses/',
      alwaysIncludePattern: true,
      maxLogSize: 104800,
      backups: 100
    }
  },
  categories: {
    error: { appenders: [ 'error' ], level: 'error' },
    response: { appenders: [ 'response' ], level: 'info' },
    default: { appenders: ['response'], level: 'info'}
  },
  replaceConsole: true
});

let errorLogger = log4js.getLogger('error')
let resLogger = log4js.getLogger('response')
// 封装错误日志
logger.errLogger = (ctx, error, resTime) => {
  if(ctx && error) {
      errorLogger.error(formatError(ctx, error, resTime))
  }
}
// 封装响应日志
logger.resLogger = (ctx, resTime) => {
  if(ctx) {
      resLogger.info(formatRes(ctx, resTime))
  }
}
module.exports = logger

